package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shogo82148/androidbinary"
	"github.com/shogo82148/androidbinary/apk"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
	"webTools/model"
	"webTools/util"
)

type appInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Icon    string `json:"icon"`
}

func GetAppInfoHandler(c *gin.Context) {
	url := c.Query("url")
	log.Println("url: ", url)
	appInfo, err := getAppInfo(url)
	var result *model.Result
	if err != nil {
		result = model.Error(1, err.Error())
	} else {
		log.Println(appInfo)
		result = model.Success(appInfo)
	}
	c.JSON(http.StatusOK, result)
}

// getAppInfo 下载app并解析
func getAppInfo(url string) (*appInfo, error) {

	file, err := downloadApp(url)
	if err != nil {
		return nil, err
	}
	defer func(name string) {
		err := os.Remove(name)
		if err != nil {
			log.Println("清除apk失败", err)
		}
	}(file.Name())

	pkg, err := apk.OpenFile(file.Name())
	if err != nil {
		fmt.Println(err)
		return nil, fmt.Errorf("解析apk失败")
	}

	defer func() {
		err := pkg.Close()
		if err != nil {
			log.Println("关闭apk失败")
		}
	}()

	pkgAppName, err := pkg.Manifest().App.Label.String()
	if err != nil {
		return nil, fmt.Errorf("解析app信息失败")
	}
	resConfigEN := &androidbinary.ResTableConfig{
		Language: [2]uint8{uint8('c'), uint8('n')},
	}

	appIconImage, err := pkg.Icon(resConfigEN)
	var appIcon string
	if err != nil {
		appIconImage = nil
	} else {
		appIcon, _ = util.ImageToBase64(appIconImage)
	}

	appVersion, err := pkg.Manifest().VersionName.String()

	appInfo := &appInfo{Icon: appIcon, Version: appVersion, Name: pkgAppName}
	return appInfo, nil
}

// downloadApp 下载app
func downloadApp(url string) (*os.File, error) {
	res, err := http.Get(url)
	if err != nil {
		log.Println(err)
		return nil, fmt.Errorf("下载app失败")
	}
	if res.StatusCode != http.StatusOK {
		log.Println(err)
		return nil, fmt.Errorf("下载app失败")
	}
	f, err := os.Create("temp" + strconv.FormatInt(time.Now().Unix(), 10) + ".apk")
	if err != nil {
		log.Println(err)
		return nil, fmt.Errorf("创建文件失败")
	}
	_, err = io.Copy(f, res.Body)
	if err != nil {
		log.Println(err)
		return nil, fmt.Errorf("保存app失败")
	}
	return f, nil
}
